<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="800px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    custom-class="judge-type-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="medium"
    >
      <el-form-item label="评价标准类型" prop="judgeType">
        <el-select
          v-model="formData.judgeType"
          placeholder="请选择评价标准类型"
          @change="handleJudgeTypeChange"
          style="width: 100%"
        >
          <el-option label="区间型" value="between" />
          <el-option label="目标型" value="top" />
          <el-option label="底线型" value="bottom" />
          <el-option label="普查型" value="normal" />
        </el-select>
      </el-form-item>

      <div class="judge-options-section">
        <div class="section-header">
          <span>评价标准模型</span>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="addJudgeOption"
          >
            新增
          </el-button>
        </div>

        <div
          v-for="(option, index) in formData.indexJudgeOptionList"
          :key="index"
          class="judge-option-item"
        >
          <el-card shadow="never" class="option-card">
            <div class="option-header">
              <span>评价项 {{ index + 1 }}</span>
              <el-button
                v-if="formData.indexJudgeOptionList.length > 1"
                type="text"
                size="small"
                icon="el-icon-delete"
                style="color: #f56c6c"
                @click="removeJudgeOption(index)"
              >
                删除
              </el-button>
            </div>

                         <el-form-item
               :prop="`indexJudgeOptionList.${index}.judgeName`"
               :rules="{ required: true, message: '请输入评价结论', trigger: 'blur' }"
               label="评价结论"
             >
               <el-input
                 v-model="option.judgeName"
                 placeholder="请输入评价结论"
                 clearable
               />
             </el-form-item>

             <!-- 区间型：>= 且 < -->
             <template v-if="formData.judgeType === 'between'">
               <el-form-item label="指标值区间">
                 <div class="condition-inline">
                   <div class="range-input-group">
                     <span>>=</span>
                     <el-form-item
                       :prop="`indexJudgeOptionList.${index}.firstValue`"
                       :rules="getRangeValidationRules(option, 'min')"
                       style="display: inline-block; margin: 0 8px; margin-bottom: 0;"
                     >
                       <el-input
                         v-model="option.firstValue"
                         placeholder="最小值"
                         style="width: 120px;"
                         @input="handleNumberInput($event, option, 'firstValue')"
                       />
                     </el-form-item>
                   </div>
                   <div class="range-input-group">
                     <span>且 &lt;</span>
                     <el-form-item
                       :prop="`indexJudgeOptionList.${index}.secondValue`"
                       :rules="getRangeValidationRules(option, 'max')"
                       style="display: inline-block; margin: 0 8px; margin-bottom: 0;"
                     >
                       <el-input
                         v-model="option.secondValue"
                         placeholder="最大值"
                         style="width: 120px;"
                         @input="handleNumberInput($event, option, 'secondValue')"
                       />
                     </el-form-item>
                   </div>
                 </div>
               </el-form-item>
             </template>

             <!-- 目标型：>= 最小值 -->
             <template v-else-if="formData.judgeType === 'top'">
               <el-form-item 
                 :prop="`indexJudgeOptionList.${index}.firstValue`"
                 :rules="{ required: true, message: '请输入最小值', trigger: 'blur' }"
                 label="指标值区间"
               >
                 <div class="condition-inline">
                   <span>>=</span>
                   <el-input
                     v-model="option.firstValue"
                     placeholder="最小值"
                     style="width: 120px; margin-left: 8px"
                     @input="handleNumberInput($event, option, 'firstValue')"
                   />
                 </div>
               </el-form-item>
             </template>

             <!-- 底线型：< 最大值 -->
             <template v-else-if="formData.judgeType === 'bottom'">
               <el-form-item 
                 :prop="`indexJudgeOptionList.${index}.secondValue`"
                 :rules="{ required: true, message: '请输入最大值', trigger: 'blur' }"
                 label="指标值区间"
               >
                 <div class="condition-inline">
                   <span>&lt;</span>
                   <el-input
                     v-model="option.secondValue"
                     placeholder="最大值"
                     style="width: 120px; margin-left: 8px"
                     @input="handleNumberInput($event, option, 'secondValue')"
                   />
                 </div>
               </el-form-item>
             </template>

             <!-- 普查型：不显示区间值 -->
          </el-card>
        </div>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { Message } from 'element-ui'
import type { ElForm } from 'element-ui/types/form'

interface JudgeOption {
  pkid?: string
  judgeName: string
  judgeMinValue?: number
  judgeMaxValue?: number
  // 新增的条件字段
  firstOperator?: string
  firstValue?: number
  logicOperator?: string
  secondOperator?: string
  secondValue?: number
}

interface JudgeFormData {
  indexId: string
  judgeType: string
  indexType: string
  indexJudgeOptionList: JudgeOption[]
}

interface Props {
  visible: boolean
  rowData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: JudgeFormData): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  rowData: () => ({})
})

const emit = defineEmits<Emits>()

const formRef = ref<ElForm>()
const submitLoading = ref(false)

const formData = reactive<JudgeFormData>({
  indexId: '',
  judgeType: '',
  indexType: '',
  indexJudgeOptionList: []
})

const formRules = {
  judgeType: [
    { required: true, message: '请选择评价标准类型', trigger: 'change' }
  ]
}

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const dialogTitle = computed(() => {
  // 判断是否为编辑模式：有 commonJudgeList 且长度大于0
  const hasExistingData = props.rowData?.commonJudgeList && props.rowData.commonJudgeList.length > 0
  return hasExistingData ? '编辑评价标准' : '添加评价标准'
})

watch(
  () => props.rowData,
  (newData) => {
    if (newData && props.visible) {
      formData.indexId = newData.pkid || ''
      formData.indexType = newData.type || ''
      
      if (newData.commonJudgeList && newData.commonJudgeList.length > 0) {
        const judgeList = newData.commonJudgeList
        const firstJudge = judgeList[0]
        
        formData.judgeType = firstJudge.judgeType || ''
        formData.indexJudgeOptionList = judgeList.map((item: any) => ({
          pkid: item.pkid,
          judgeName: item.judgeName || '',
          judgeMinValue: item.judgeMinValue,
          judgeMaxValue: item.judgeMaxValue,
          firstValue: item.judgeMinValue,
          secondValue: item.judgeMaxValue
        }))
      } else {
        formData.judgeType = ''
        formData.indexJudgeOptionList = [createEmptyOption()]
      }
    }
  },
  { immediate: true, deep: true }
)

watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      const newData = props.rowData
      if (newData) {
        formData.indexId = newData.pkid || ''
        formData.indexType = newData.type || ''
        
        if (newData.commonJudgeList && newData.commonJudgeList.length > 0) {
          const judgeList = newData.commonJudgeList
          const firstJudge = judgeList[0]
          
          formData.judgeType = firstJudge.judgeType || ''
          formData.indexJudgeOptionList = judgeList.map((item: any) => ({
            pkid: item.pkid,
            judgeName: item.judgeName || '',
            judgeMinValue: item.judgeMinValue,
            judgeMaxValue: item.judgeMaxValue,
            firstValue: item.judgeMinValue,
            secondValue: item.judgeMaxValue
          }))
        } else {
          formData.judgeType = ''
          formData.indexJudgeOptionList = [createEmptyOption()]
        }
      }
      
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
  }
)

const createEmptyOption = (): JudgeOption => ({
  judgeName: '',
  judgeMinValue: undefined,
  judgeMaxValue: undefined,
  firstValue: undefined,
  secondValue: undefined
})

const handleJudgeTypeChange = () => {
  formData.indexJudgeOptionList.forEach(option => {
    option.firstValue = undefined
    option.secondValue = undefined
    
    option.judgeMinValue = undefined
    option.judgeMaxValue = undefined
  })
}

const addJudgeOption = () => {
  formData.indexJudgeOptionList.push(createEmptyOption())
}

const removeJudgeOption = (index: number) => {
  if (formData.indexJudgeOptionList.length > 1) {
    formData.indexJudgeOptionList.splice(index, 1)
  }
}

const handleNumberInput = (value: string, option: JudgeOption, field: 'firstValue' | 'secondValue') => {
  const numericValue = value.replace(/[^0-9.-]/g, '')
  
  const parsedValue = parseFloat(numericValue)
  
  if (!isNaN(parsedValue)) {
    option[field] = parsedValue
  } else if (numericValue === '' || numericValue === '-' || numericValue.endsWith('.')) {
    option[field] = numericValue as any
  }
  
  // 在数值变化后触发校验，延迟执行避免过于频繁
  nextTick(() => {
    if (formRef.value) {
      const index = formData.indexJudgeOptionList.findIndex(item => item === option)
      if (index !== -1) {
        // 触发对应字段的校验
        formRef.value.validateField(`indexJudgeOptionList.${index}.${field}`)
        // 如果是区间型，同时校验另一个字段
        if (formData.judgeType === 'between') {
          const otherField = field === 'firstValue' ? 'secondValue' : 'firstValue'
          const otherValue = option[otherField]
          if (otherValue !== undefined && otherValue !== null && String(otherValue).trim() !== '') {
            formRef.value.validateField(`indexJudgeOptionList.${index}.${otherField}`)
          }
        }
      }
    }
  })
}

const getRangeValidationRules = (option: JudgeOption, type: 'min' | 'max') => {
  const rules: any[] = []
  
  if (type === 'min') {
    rules.push({ required: true, message: '请输入最小值', trigger: 'blur' })
    rules.push({
      validator: (rule: any, value: any, callback: any) => {
        if (!value && value !== 0) {
          callback(new Error('请输入最小值'))
          return
        }
        
        const minValue = parseFloat(value)
        const maxValue = parseFloat(option.secondValue as any)
        
        if (isNaN(minValue)) {
          callback(new Error('请输入有效的数字'))
          return
        }
        
        // 检查最小值是否大于等于最大值
        if (!isNaN(maxValue) && minValue >= maxValue) {
          callback(new Error('最小值不能大于等于最大值'))
          return
        }
        
        callback()
      },
      trigger: ['blur', 'change']
    })
  } else {
    rules.push({ required: true, message: '请输入最大值', trigger: 'blur' })
    rules.push({
      validator: (rule: any, value: any, callback: any) => {
        if (!value && value !== 0) {
          callback(new Error('请输入最大值'))
          return
        }
        
        const maxValue = parseFloat(value)
        const minValue = parseFloat(option.firstValue as any)
        
        if (isNaN(maxValue)) {
          callback(new Error('请输入有效的数字'))
          return
        }
        
        // 检查最大值是否小于等于最小值
        if (!isNaN(minValue) && maxValue <= minValue) {
          callback(new Error('最大值不能小于等于最小值'))
          return
        }
        
        callback()
      },
      trigger: ['blur', 'change']
    })
  }
  
  return rules
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return

    // 额外的数据校验（防止前端校验被绕过）
    if (formData.judgeType === 'between') {
      for (let i = 0; i < formData.indexJudgeOptionList.length; i++) {
        const option = formData.indexJudgeOptionList[i]
        const minValue = parseFloat(option.firstValue as any)
        const maxValue = parseFloat(option.secondValue as any)
        
        if (!isNaN(minValue) && !isNaN(maxValue) && minValue >= maxValue) {
          Message.error(`评价项 ${i + 1} 的最小值不能大于等于最大值`)
          return
        }
      }
    }

    submitLoading.value = true
    
    const submitData: JudgeFormData = {
      indexId: formData.indexId,
      judgeType: formData.judgeType,
      indexType: formData.indexType,
      indexJudgeOptionList: formData.indexJudgeOptionList.map(option => {
        const result: any = {
          judgeName: option.judgeName
        }
        
        if (option.pkid) {
          result.pkid = option.pkid
        }
        
        if (formData.judgeType === 'between') {
          // 区间型：>= 且 <
          result.judgeMinValue = option.firstValue || 0
          result.judgeMaxValue = option.secondValue || 0
        } else if (formData.judgeType === 'top') {
          // 目标型：>= 最小值
          result.judgeMinValue = option.firstValue || 0
          result.judgeMaxValue = 0
        } else if (formData.judgeType === 'bottom') {
          // 底线型：< 最大值
          result.judgeMinValue = 0
          result.judgeMaxValue = option.secondValue || 0
        } else if (formData.judgeType === 'normal') {
          // 普查型：无条件
          result.judgeMinValue = 0
          result.judgeMaxValue = 0
        }
        
        return result
      })
    }
    
    emit('submit', submitData)
    handleClose()
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.judge-options-section {
  margin-top: 20px;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    
    span {
      font-weight: 500;
      color: #303133;
    }
  }
}

.judge-option-item {
  margin-bottom: 15px;
  
  .option-card {
    border: 1px solid #ebeef5;
    
    :deep(.el-card__body) {
      padding: 15px;
    }
  }
  
  .option-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    span {
      font-weight: 500;
      color: #606266;
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.condition-inline {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  
  span {
    font-weight: 500;
    color: #606266;
    white-space: nowrap;
    line-height: 32px; /* 与输入框高度对齐 */
  }
}

.range-input-group {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}
</style>

<style lang="scss">
.judge-type-dialog {
  .el-dialog {
    max-height: 70vh;
    display: flex;
    flex-direction: column;
  }
  
  .el-dialog__header {
    flex-shrink: 0;
  }
  
  .el-dialog__body {
    flex: 1;
    overflow-y: auto;
    max-height: calc(70vh - 120px);
    padding: 20px;
  }
  
  .el-dialog__footer {
    flex-shrink: 0;
  }
}
</style> 